package com.bwie.service.impl;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Menu;
import com.bwie.common.utils.JwtUtils;
import com.bwie.mapper.MenuMapper;
import com.bwie.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @className: MenuServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 刘鑫
 * @date: 2025/8/24 14:24
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;

    @Override
    public List<Menu> menuTree() {
        //获取角色id
        String token = request.getHeader(TokenConstants.TOKEN);
        Integer roleId = (Integer) redisTemplate.opsForValue().get(TokenConstants.ROLE_ID + token);
        System.out.println(roleId);

        //根据角色id查询对应的权限
        List<Menu> menuList=menuMapper.menuList(roleId);
        Map<Integer, List<Menu>> collect = menuList.stream().collect(Collectors.groupingBy(Menu::getMenuPid));
        //递归
        List<Menu> getMenuList=getMenuList(collect,0);
        return getMenuList;
    }

    private List<Menu> getMenuList(Map<Integer, List<Menu>> collect, int pid) {
        List<Menu> menuList = collect.get(pid);
        if (menuList!=null){
            menuList.forEach(menu -> {
                List<Menu> reqList = getMenuList(collect, menu.getMenuId());
                menu.setChildrend(reqList);
            });
        }
        return menuList;
    }
}
